import axios from 'axios'
import { message } from 'ant-design-vue'
import 'ant-design-vue/lib/message/style/index.css'

import store from '@/store/index.js'
const https = axios.create({
	baseURL: import.meta.env.VITE_BASE_URL,
	timeout: 1000,
	headers: { 'X-Custom-Header': 'foobar' },
})

// Add a request interceptor
https.interceptors.request.use(
	function (config) {
		if (store.state.index.logeed) {
			// 登录状态 验证成功
			// 添加请求头信息 token凭证
			config.headers.Authorization = `${store.state.index.tokenList.tokenType} ${store.state.index.tokenList.accessToken}`
		}
		// 请求头添加组织代码
		if (store.state.index.organizationList) {
			config.headers.organizationList = store.state.index.member.code
		}
		// Do something before request is sent
		return config
	},
	function (error) {
		// Do something with request error
		return Promise.reject(error)
	}
)

// Add a response interceptor
https.interceptors.response.use(
	function (response) {
		// Any status code that lie within the range of 2xx cause this function to trigger
		if (response.status === 200) {
			return response.data
		}
		// 不为200的 基本都是错误的，选择性的单独处理
		message.warning(response.data.msg)
		// Do something with response data
		return response
	},
	function (error) {
		// Any status codes that falls outside the range of 2xx cause this function to trigger
		// Do something with response error
		return Promise.reject(error)
	}
)

export default https
